package com.dyz.leetcode;

import java.util.Arrays;

public class NumSquares279 {
    public static void main(String[] args) {
        new NumSquares279().numSquares(5);
    }
    public int numSquares(int n) {
        int[] dp = new int[n+1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for(int i=0; i<n;i++){
            for(int j=1; i+j*j<=n;j++){
                if(dp[i]+1<dp[i+j*j]){
                    dp[i+j*j]=dp[i]+1;
                }
            }
        }
        return dp[n];
    }

    public int numSquares1(int n) {
        //动态规划
        //dp[0]=0
        //dp[i] = Math.min(dp[i-j*j])+1; 1<j<i*i
        int [] dp = new int[n+1];
        for(int i=1; i<=n; i++){
            int upper = (int)Math.sqrt(i);
            for(int j=1; j<=upper; j++){
                dp[i] = dp[i]==0?dp[i-j*j]:Math.min(dp[i], dp[i-j*j]);
            }
            dp[i]+=1;
        }
        return dp[n];
    }
}
